﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace Dracham.MapEditor.Maps
{
    public class ZoneManager
    {
        private XmlDocument xZone;
        private String xmlFile = "";
        public List<Zone> Zones { get; set; }

        public ZoneManager(String appPath)
        {
            this.xmlFile = appPath  + "zones.xml";

            xZone = new XmlDocument();

            if (!File.Exists(this.xmlFile))
            {
                File.WriteAllText(this.xmlFile, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n<Zones></Zones>");
            }

            xZone.Load(this.xmlFile);

            LoadZones();
        }

        public XmlAttribute CreateAttribute(String name, String value)
        {
            XmlAttribute attrib = xZone.CreateAttribute(name);
            attrib.Value = value;

            return attrib;
        }

        public XmlNode CreateElement(String name)
        {
            XmlNode node = xZone.CreateElement(name);

            return node;
        }

        public Zone CreateZone(String name, String id, String enterZoneText, Int32 width, Int32 height)
        {
            Zone z = new Zone(name, id, enterZoneText, width, height);
            this.Zones.Add(z);

            XmlNode zoneNode = xZone.CreateElement("Zone");
            z.WriteToXmlNode(ref zoneNode);

            xZone.GetElementsByTagName("Zones")[0].AppendChild(zoneNode);
            this.SaveXml();

            return z;
        }

        private void SaveXml()
        {
            xZone.Save(this.xmlFile);
        }

        private void LoadZones()
        {
            this.Zones = new List<Zone>();
            foreach (XmlNode mapNode in xZone.GetElementsByTagName("Zone"))
            {
                Zones.Add(Zone.FromXmlNode(mapNode));
            }
        }

        public void SaveZone(Zone zone)
        {
            XmlNodeList zonesNode = xZone.GetElementsByTagName("Zone");
            for(Int32 i = 0; i < zonesNode.Count;i++)
            {
                if (zonesNode[i].Attributes["Name"].Value == zone.Name)
                {
                    XmlNode n = zonesNode[i];
                    zone.WriteToXmlNode(ref n);
                    SaveXml();

                    break;
                }
            }
        }

        public Zone GetZone(String zoneName)
        {
            return this.Zones.Where(z => z.Name == zoneName).SingleOrDefault();
        }

        public XmlDocument GetXmlDocument()
        {
            return xZone;
        }

        public Zone GetZoneById(string zoneId)
        {
            return this.Zones.Where(z => z.Id == zoneId).SingleOrDefault();
        }
    }
}
